﻿namespace EyeOpen.SilverlightConverter.Windows
{
    using System;
    using System.Collections.Generic;
    using System.Windows.Forms;

    internal static class Program
    {
        private static IList<IErrorSubscriber> errorsSubscribers = null;

        [STAThread]
        private static void Main()
        {
            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);
            Application.ThreadException += new System.Threading.ThreadExceptionEventHandler(Application_ThreadException);
            AppDomain.CurrentDomain.UnhandledException += new UnhandledExceptionEventHandler(CurrentDomain_UnhandledException);

            errorsSubscribers = new List<IErrorSubscriber>();

            MainForm mainForm = new MainForm();            
            errorsSubscribers.Add(mainForm);

            Application.Run(mainForm);
        }

        private static void Application_ThreadException(object sender, System.Threading.ThreadExceptionEventArgs e)
        {
            HandleException(errorsSubscribers, e.Exception);
        }

        private static void CurrentDomain_UnhandledException(object sender, UnhandledExceptionEventArgs e)
        {
            HandleException(errorsSubscribers, (Exception)e.ExceptionObject);
        }

        private static void HandleException(IList<IErrorSubscriber> errorsSubscribers, Exception lastError)
        {
            try
            {
                foreach (IErrorSubscriber subscriber in errorsSubscribers)
                {
                    subscriber.RegisterError(lastError);
                }
            }
            catch 
            {
            }
        }
    }
}